package com.start_eternity.oasissafewalk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.start_eternity.oasissafewalk.mapper.CarMapper;
import com.start_eternity.oasissafewalk.pojo.Car;
import com.start_eternity.oasissafewalk.pojo.Driver;
import com.start_eternity.oasissafewalk.pojo.Logg;
import com.start_eternity.oasissafewalk.pojo.PageBean;
import com.start_eternity.oasissafewalk.service.CarService;
import com.start_eternity.oasissafewalk.service.LoggService;
import com.start_eternity.oasissafewalk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private LoggService loggService;
    @Autowired
    private HttpServletRequest request;
    @Override
    public PageBean page(Integer page, Integer pageSize, String name) {
        //1.设置分页参数
        PageHelper.startPage(page,pageSize);

        //2.执行查询
        List<Car> carList = carMapper.list(name);
        Page<Car> p=(Page<Car>)carList;
        //3.封装PageBean对象
        return new PageBean(p.getTotal(),p.getResult());
    }
    @Override//删除
    public void delete(List<Integer> ids) {
        carMapper.delete(ids);
        //用logg记录
        Logg logg = new Logg();
        logg.setLoggTime(LocalDateTime.now());//记录执行的当前时间
        //获取请求头中的jwt令牌, 解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        String name = (String) claims.get("username");
        logg.setLoggName(name);//记录执行者的名字
        logg.setLoggDescription("执行了删除车辆的操作，此次删除的车辆是"+ids+"号车辆");//记录执行的具体操作
        loggService.insert(logg);//调用loggService接口将logg类的信息记录到数据库里面
    }
    @Override//新增
    public void add(Car car) {

        car.setCreateTime(LocalDateTime.now());
        car.setUpdateTime(LocalDateTime.now());
        carMapper.insert(car);

        //用logg记录
        Logg logg = new Logg();
        logg.setLoggTime(LocalDateTime.now());//记录执行的当前时间
        //获取请求头中的jwt令牌, 解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        String name = (String) claims.get("username");
        logg.setLoggName(name);//记录执行者的名字
        logg.setLoggDescription("执行了新增车辆的操作，此次新增车辆名称:"+car.getCarName());//记录执行的具体操作
        loggService.insert(logg);//调用loggService接口将logg类的信息记录到数据库里面
    }
    @Override
    public Car getById(Integer carId) {
        return carMapper.getById(carId);
    }

    @Override
    public void update(Car car) {
        car.setUpdateTime(LocalDateTime.now());
        carMapper.update(car);
    }
}
